package com.nami.store.biz.grphismsgs.repository.impl;

import cn.hutool.core.collection.CollUtil;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.nami.store.api.request.message.HisMsgQryRequest;
import com.nami.store.api.response.message.MessageDTO;
import com.nami.store.biz.grphismsgs.repository.GrpHisMsgsRepository;
import com.nami.store.domain.GrpHisMsgsDO;
import com.nami.store.mapper.GrpHisMsgsMapper;
import lombok.AllArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Service;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.function.Function;
import java.util.stream.Collectors;

/**
 * <p>
 *
 * </p>
 *
 * @author lbc
 * @since 2024-06-15
 */
@Service
@Slf4j
@AllArgsConstructor
public class GrpHisMsgsServiceImpl implements GrpHisMsgsRepository {

    private final GrpHisMsgsMapper baseMapper;

    @Override
    public boolean save(GrpHisMsgsDO msgs) {
        baseMapper.insert(msgs);
        return Boolean.TRUE;
    }

    @Override
    public Map<String, MessageDTO> getMsgs(List<String> grpMsgIds) {
        if (CollUtil.isEmpty(grpMsgIds)) {
            return new HashMap<>();
        }
        List<GrpHisMsgsDO> msgList = baseMapper.selectList(new LambdaQueryWrapper<GrpHisMsgsDO>().in(GrpHisMsgsDO::getMsgId, grpMsgIds));
        if (CollUtil.isEmpty(msgList)) {
            return new HashMap<>();
        }

        List<MessageDTO> messages = new ArrayList<>();
        MessageDTO messageVO;
        for (GrpHisMsgsDO item : msgList) {
            messageVO = new MessageDTO();
            messageVO.setPayload(item.getPayload());
            messageVO.setPayloadType(item.getPayloadType());
            messageVO.setSeq(item.getSeq());
            messageVO.setMemberCount(item.getMemberCount());
            messageVO.setReadCount(item.getReadCount());
            messageVO.setId(item.getMsgId());
            messageVO.setSendTime(item.getSendTime());

            messages.add(messageVO);
        }

        return messages.stream().collect(Collectors.toMap(MessageDTO::getId, Function.identity()));
    }

    @Override
    public List<GrpHisMsgsDO> getGrpHisMsgs(HisMsgQryRequest request) {
        List<GrpHisMsgsDO> result = baseMapper.selectList(new LambdaQueryWrapper<GrpHisMsgsDO>()
            .eq(GrpHisMsgsDO::getAppKey, request.getAppKey())
            .eq(GrpHisMsgsDO::getConverId, request.getConverId())
            .lt(request.getLastSeq() != null, GrpHisMsgsDO::getSeq, request.getLastSeq())
            .orderByDesc(GrpHisMsgsDO::getSeq)
            .last(" limit " + request.getPageSize())
        );
        return result;
    }
}
